﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Server;
using System.ServiceModel.Description;
using System.Net;
using TFS_2010_Warehouse_Updater.Properties;

namespace TFS_2010_Warehouse_Updater
{
    public partial class frmMain : Form
    {
        DateTime JobStart = new DateTime();

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Settings.Default.Server) || string.IsNullOrEmpty(Settings.Default.Collection))
            {
                ShowSettings();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {           
            try
            {
                TFSReference.WarehouseControlWebServiceSoapClient service = GetTFSService();
                TFSReference.GetProcessingStatusResponse status = service.GetProcessingStatus(new TFSReference.GetProcessingStatusRequest());
                if (status.WarehouseProcessingStatus.JobProcessingStatus == TFSReference.ProcessingStatus.Idle)
                {
                    UpdateComplete();
                }                
            }
            catch (Exception ex)
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                MessageBox.Show(ex.Message);
            }
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowSettings();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            TimeSpan jobTime = DateTime.Now - JobStart;
            notifyIcon1.Text = string.Format("{0}:{1} Updating...", jobTime.Minutes, jobTime.Seconds.ToString().PadLeft(2, '0'));
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // Set the WindowState to normal if the form is minimized.
            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            
            contextMenuStrip1.Show();
        }

        //private void frmMain_Resize(object sender, EventArgs e)
        //{
        //    //if (FormWindowState.Minimized == WindowState)
        //    this.Hide();
        //}

        private void settingsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ShowSettings();
        }

        private void startUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StartUpdate();
        }

        private void StartUpdate()
        {
            try
            {
                TFSReference.WarehouseControlWebServiceSoapClient service = GetTFSService();
                service.ProcessWarehouse(new TFSReference.ProcessWarehouseRequest(Settings.Default.Collection, ""));
                service.ProcessAnalysisDatabase(new TFSReference.ProcessAnalysisDatabaseRequest(TFSReference.AnalysisDatabaseProcessingType.Full));
                timer1.Enabled = true;
                timer2.Enabled = true;
                startUpdateToolStripMenuItem.Enabled = false;
                JobStart = DateTime.Now;
                notifyIcon1.Text = string.Format("Update Started at {0} {1}.", JobStart.ToShortDateString(), JobStart.ToShortTimeString());
                notifyIcon1.ShowBalloonTip(3, "Update Started.", string.Format("Update Started at {0} {1}.", JobStart.ToShortDateString(), JobStart.ToShortTimeString()), ToolTipIcon.Info);
            }
            catch (Exception ex)
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                MessageBox.Show(ex.Message);
            }
        }

        private void ShowSettings()
        {
            frmSettings settings = new frmSettings();
            settings.Show();
        }

        private TFSReference.WarehouseControlWebServiceSoapClient GetTFSService()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Ntlm;
            binding.UseDefaultWebProxy = false;
            string ServerAddress = string.Format(@"http://{0}:{1}/tfs/TeamFoundation/Administration/v3.0/WarehouseControlService.asmx", Settings.Default.Server, Settings.Default.Port);
            EndpointAddress addr = new EndpointAddress(ServerAddress);
            TFSReference.WarehouseControlWebServiceSoapClient service = new TFSReference.WarehouseControlWebServiceSoapClient(binding, addr);
            ClientCredentials creds = service.ClientCredentials;
            creds.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            creds.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Identification;
            return service;
        }

        private void UpdateComplete()
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
            TimeSpan jobTime = DateTime.Now - JobStart;
            notifyIcon1.Text = string.Format("{0}:{1} Update Completed {2} {3}.", jobTime.Minutes, jobTime.Seconds.ToString().PadLeft(2, '0'), JobStart.ToShortDateString(), JobStart.ToShortTimeString());
            notifyIcon1.ShowBalloonTip(3, "Update Complete.", string.Format("{0}:{1} Update Completed {2} {3}.", jobTime.Minutes, jobTime.Seconds.ToString().PadLeft(2, '0'), JobStart.ToShortDateString(), JobStart.ToShortTimeString()), ToolTipIcon.Info);
            startUpdateToolStripMenuItem.Enabled = true;
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(Settings.Default.Server))
                startUpdateToolStripMenuItem.Enabled = false;
            else
                startUpdateToolStripMenuItem.Enabled = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            ShowSettings();
        }

        private void btnStartUpdate_Click(object sender, EventArgs e)
        {
            StartUpdate();
        }
    }
}
